<template>
  <el-card shadow="never" class="border-0">
    <el-collapse v-model="projectActiveNames">
      <el-collapse-item title="基础信息" name="shipInfo">
        <el-row :gutter="10" class="basis-layout">
          <el-col :span="12">
            <el-descriptions :column="2" size="small" v-if="shipDetail">
              <el-descriptions-item label="船名">{{ shipDetail.name }}</el-descriptions-item>
              <el-descriptions-item label="IMO">{{ shipDetail.imo }}</el-descriptions-item>
              <el-descriptions-item label="MMSI">{{ shipDetail.mmsi }}</el-descriptions-item>
              <el-descriptions-item label="归属项目">{{ shipDetail.projectName }}</el-descriptions-item>
              <el-descriptions-item label="船舶类型">{{ shipDetail.shipType }}</el-descriptions-item>
              <el-descriptions-item label="登记日期">{{ shipDetail.createTime }}</el-descriptions-item>
            </el-descriptions>
            <div class="flex items-center justify-between">
              <span class="product-title">产品信息</span>
              <el-button type="primary" @click="openAddProductDialog" size="small" class="ml-auto">新增产品</el-button>
              <el-button type="info" @click="selectProduct" size="small">选择产品</el-button>
              <el-button @click="handleImport" size="small">导入Excel</el-button>
            </div>
            <el-table :data="filteredProducts" size="small" height="120" style="width: 100%" highlight-current-row
              @current-change="handleProductSelect" empty-text="暂无产品或添加新产品">
              <el-table-column label="产品型号">
                <template #default="{ row }">
                  {{ row.productTypeCode }}
                </template>
              </el-table-column>
              <el-table-column label="整机号" width="140">
                <template #default="{ row }">
                  {{ row.oeSerialNo }}
                </template>
              </el-table-column>
              <el-table-column label="质保状态">
                <template #default="{ row }">
                  {{ transferProductStatus(row.warrantyEndDate) }}
                </template>
              </el-table-column>
              <el-table-column label="操作" width="90">
                <template #default="{ row }">
                  <el-button @click="toggleProductExpand(row)" style="font-size: 12px;color: #409eff" link>
                    {{ expandedProduct === row.productId ? '收起' : '展开' }}
                  </el-button>
                  <el-button @click="removeProduct(row)" style="font-size: 12px;color: #f56c6c" link>移除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-col>
          <el-col :span="12">
            <div class="flex items-center justify-between">
              <span class="section-title">部件列表</span>
              <el-button size="small" style="color: #409eff" @click="showAddSparePartDialog" :disabled="!currentProduct"
                link>
                添加部件
              </el-button>
            </div>

            <template v-if="currentProduct">
              <div class="product-info">
                <h6>{{ currentProduct.productTypeCode }}</h6>
                <p>整机号: {{ currentProduct.oeSerialNo }}</p>
                <p v-if="currentProduct.deliveryDate && currentProduct.warrantyEndDate">
                  质保截止日期: {{ dateFormatterDay(currentProduct.deliveryDate) }} 至 {{
                  dateFormatterDay(currentProduct.warrantyEndDate) }}
                </p>
                <p v-if="currentProduct.shipDeliveryDate && currentProduct.warrantyEndDate">
                  质保截止日期: {{ dateFormatterDay(currentProduct.shipDeliveryDate) }} 至 {{
                  dateFormatterDay(currentProduct.warrantyEndDate) }}
                </p>
                <p v-else>
                  质保截止日期: 暂无
                </p>
              </div>

              <el-table :data="currentProduct.productPartDto" border height="120" size="small" empty-text="该产品暂无备件"
                v-if="expandedProduct === currentProduct.productId">
                <el-table-column prop="partName" label="品名" show-overflow-tooltip></el-table-column>
                <el-table-column prop="partTypeId" label="型号"></el-table-column>
                <el-table-column prop="partSn" label="序列号" width="120"></el-table-column>
                <el-table-column label="操作" width="120">
                  <template #default="scope">
                    <el-button link @click="editSparePart(scope.row)"
                      style="font-size: 12px;color: #409eff">编辑</el-button>
                    <el-button link style="font-size: 12px;color: #f56c6c" @click="removeSparePart(scope.row.partId)">
                      删除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </template>

            <div class="empty-tip" v-else>
              <el-empty description="请从左侧选择产品"></el-empty>
            </div>
          </el-col>
        </el-row>
      </el-collapse-item>


    </el-collapse>
    <br />

    <el-form label-width="80px" class="mb-3" size="small">
      <el-row :gutter="20">
        <el-col :span="5" :offset="0">
          <el-form-item label="工单号">
            <el-input v-model="searchForm.orderNo" placeholder="工单号" clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="5" :offset="0">
          <el-form-item label="工单名称">
            <el-input v-model="searchForm.orderName" placeholder="工单名称" clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="工单状态">
            <el-select v-model="searchForm.orderStatus" placeholder="工单状态" clearable>
              <el-option v-for="item in orderStatusList" :key="item.code" :label="item.description"
                :value="item.code" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <div class="flex items-center justify-end">
            <el-button type="primary" @click="getData">搜索</el-button>
            <el-button @click="resetSearchForm">重置</el-button>
          </div>
        </el-col>
      </el-row>
    </el-form>
    <div class="flex items-center justify-between mb-4">
      <el-button type="primary" size="small" @click="handleOrderDialog">新增工单</el-button>
      <el-tooltip effect="dark" content="刷新数据" placement="top">
        <el-button link @click="getData">
          <el-icon :size="20">
            <Refresh />
          </el-icon>
        </el-button>
      </el-tooltip>
    </div>
    <el-table :data="workOrderList" border style="width: 100%" size="small" v-loading="loading">
      <el-table-column prop="orderNo" label="工单号" align="center" width="130" show-overflow-tooltip></el-table-column>
      <el-table-column prop="orderName" label="工单名称" align="center" width="180"></el-table-column>
      <el-table-column label="工单类型" align="center">
        <template #default="{ row }">
          {{ formatOrderType(row.orderType) }}
        </template>
      </el-table-column>
      <el-table-column label="工单发布人" align="center">
        <template #default="{ row }">
          {{ row.createUserName }}
        </template>
      </el-table-column>
      <el-table-column label="工单执行人" align="center">
        <template #default="{ row }">
          {{ row.engineerNames ? row.engineerNames : "暂无" }}
        </template>
      </el-table-column>
      <el-table-column label="工单状态" width="120" align="center">
        <template #default="{ row }">
          {{ formatOrderStatus(row.orderStatus) }}
        </template>
      </el-table-column>
      <el-table-column label="开始时间" width="120" align="center" show-overflow-tooltip>
        <template #default="{ row }">
          {{ row.startTime ? dateFormatterDay(row.startTime) : "-" }}
        </template>
      </el-table-column>
      <el-table-column label="预估工时（天）" width="120" align="center" show-overflow-tooltip>
        <template #default="{ row }">
          {{ row.estimatedHours ? row.estimatedHours : "-" }}
        </template>
      </el-table-column>
      <el-table-column label="订单来源" align="center" width="120">
        <template #default="{ row }">
          {{ row.orderSource || "-" }}
        </template>
      </el-table-column>
      <el-table-column label="设备型号" align="center" width="120" show-overflow-tooltip>
        <template #default="{ row }">
          {{ getDeviceNames(row.deviceIds) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" align="center" fixed="right">
        <template #default="scope">
          <div class="operation-buttons">
            <el-button type="warning" size="small" @click="handleEdit(scope.row)">修改</el-button>
            <el-button type="primary" size="small" @click="showPublishWin(scope.row)"
              :disabled="scope.row.orderStatus >5 ">发布</el-button>
            <el-dropdown type="danger" split-button size="small" @command="handleCommand">
              更多
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item :command="{ action: 'handleOrderLog', row: scope.row }">日志</el-dropdown-item>
                  <el-dropdown-item :command="{ action: 'handleOrderPayment', row: scope.row }"
                    :disabled="scope.row.orderStatus !== 6">回款</el-dropdown-item>
                  <el-dropdown-item :command="{ action: 'handleOrderOver', row: scope.row }"
                    :disabled="scope.row.orderStatus !== 7">结单</el-dropdown-item>
                  <el-dropdown-item :command="{ action: 'handleScore', row: scope.row }"
                    :disabled="scope.row.orderStatus !== 8">内部评分</el-dropdown-item>
                  <el-dropdown-item :command="{ action: 'customerScore', row: scope.row }">客户评分</el-dropdown-item>
                  <el-dropdown-item :command="{ action: 'showFilesEn', row: scope.row }">施工档案</el-dropdown-item>
                  <el-dropdown-item :command="{ action: 'showFiles', row: scope.row }">附件</el-dropdown-item>
                  <el-dropdown-item :command="{ action: 'handleDelete', row: scope.row }"
                    :disabled="scope.row.orderStatus !== 1 && scope.row.orderStatus !== 9">删除</el-dropdown-item>

                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- 工单table分页组件 -->
    <div class="flex items-center justify-center mt-5">
      <el-pagination background layout="prev, pager ,next" :total="total" :current-page="currentPage" :page-size="limit"
        @current-change="getData" />
    </div>

    <el-dialog v-model="batchformDrawer" title="批量产品入库" align-center>
      <el-form :model="ruleForm" label-width="120px" :inline="false">
        <el-form-item label="模板下载：">
          <el-link type="primary" :underline="false" @click="downloadTemplate">批量产品上传模板下载</el-link>
        </el-form-item>
        <!-- 添加文件上传组件 -->
        <el-form-item label="上传附件：" prop="files">
          <el-upload class="hide" action="" accept=".xlsx,.xls" :multiple="true" :on-change="handleChange"
            :file-list="ruleForm.fileList" :http-request="handleUpload" :auto-upload="true">
            <el-button slot="trigger" type="primary" plain>上传文件</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit" style="width: 35%">开始导入</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 附件弹窗 -->
    <el-dialog v-model="dialogTableVisible_orderFiles" :title="dialogTable_orderFiles_title" width="700" align-center>
      <OrderFiles v-if="dialogTableVisible_orderFiles" :orderId="currOrderFiles_orderId"
        :fileType="dialogTable_orderFiles_type" />
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="dialogTableVisible_orderFiles = false">
            关闭
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 选取位置dialog -->
    <SystemDialog title="选取地点坐标" :visible="setLocationDialogVisible" :height="50" :width="60" @on-close="closeAddress"
      @on-confirm="commitAddress" :showCloseBtn="true" :showOkBtn="true" okBtnName="确认">
      <template v-slot:content>
        <GaoDeMap v-if="setLocationDialogVisible" :addressClick="addressClick" ref="mapRef" @address="getAddress">
        </GaoDeMap>
      </template>
    </SystemDialog>

    <!-- 选取工程师dialog -->
    <SystemDialog title="选择工程师" :visible="asignEngineerDialogVisible" :height="50" :width="60"
      @on-close="closeAssignEngineer" @on-confirm="commitAssignEngineer" :showCloseBtn="true" :showOkBtn="true"
      okBtnName="确认">
      <template v-slot:content>
        <SelectEngineer v-if="asignEngineerDialogVisible" @getCheckedEngineer="getCheckedEngineer"
          :assignProps="assignProps.assignedUserId"></SelectEngineer>
      </template>
    </SystemDialog>

    <!-- 选取工程师Map dialog -->
    <SystemDialog title="选择工程师" :visible="asignEngineerMapDialogVisible" :height="50" :width="60"
      @on-close="closeAssignMapEngineer" @on-confirm="commitAssignMapEngineer" :showCloseBtn="true" :showOkBtn="true"
      okBtnName="确认">
      <template v-slot:content>
        <SelectEngineerMap v-if="asignEngineerMapDialogVisible" @getCheckedMapEngineer="getCheckedMapEngineer"
          :assignMapProps="assignProps"></SelectEngineerMap>
      </template>
    </SystemDialog>
    <SystemDialog title="查看日志" :visible="dialogTableVisible_orderLog" :height="50" :width="70" :showOkBtn="false"
      :showCloseBtn="true" okBtnName="确认" @on-close="dialogTableVisible_orderLog = false"
      @on-confirm="dialogTableVisible_orderLog = false">
      <template v-slot:content>
        <OrderLog v-if="dialogTableVisible_orderLog" :orderDetail="currOrderLog_orderDetail" />
      </template>
    </SystemDialog>

    <FormDrawer ref="formOrderDrawerRef" size="60%" :title="drawerOrderTitle" @submit="handleOrderSubmit">
      <el-form :model="orderForm" ref="orderFormRef" :rules="orderRules" label-width="90px" :inline="false">
        <el-row>
          <el-col :span="10">
            <el-form-item label="工单名称" prop="orderName">
              <el-input v-model="orderForm.orderName" placeholder="船名-设备名" @change="addTimestamp" maxlength="50"
                show-word-limit></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="工单类型" prop="orderType">
              <el-select v-model="orderForm.orderType" filterable placeholder="工单类型">
                <el-option v-for="item in orderTypes" :key="item.code" :label="item.description" :value="item.code" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="10">
            <el-form-item label="订单来源" prop="orderSource">
              <el-input v-model="orderForm.orderSource" placeholder="请选择或输入订单来源" @focus="showOrderSourceDropdown = true" clearable>
                <template #prepend>
                  <el-select v-model="selectedOrderSource" placeholder="选择" style="width: 120px" @change="handleOrderSourceSelect" >
                    <el-option label="HLD-TZ" value="HLD-TZ" />
                    <el-option label="HLD-MP" value="HLD-MP" />
                    <el-option label="HMAP" value="HMAP" />
                    <el-option label="DL-" value="DL-" />
                    <el-option label="SO-" value="SO-" />
                    <el-option label="SM-" value="SM-" />
                  </el-select>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="设备型号" prop="deviceIds">
              <el-select v-model="orderForm.deviceIds" multiple clearable collapse-tags placeholder="Select"
                popper-class="custom-header" :max-collapse-tags="1">
                <template #header>
                  <el-checkbox v-model="checkAll" @change="handleCheckAll">
                    All
                  </el-checkbox>
                </template>
                <el-option v-for="product in filteredProducts" :key="product.productId" :label="product.productTypeCode"
                  :value="product.productId" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="10">
            <el-form-item label="开始时间" prop="startTime">
              <el-date-picker v-model="orderForm.startTime" type="date" placeholder="客户要求时间" format="YYYY-MM-DD"
                value-format="YYYY-MM-DD">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="预估工时" prop="estimatedHours">
              <el-input-number v-model="orderForm.estimatedHours" placeholder="预估工时" :min="0" :precision="1"
                :step="0.5">
              </el-input-number>
              <span class="px-2">天</span>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="10">
            <el-form-item label="工单金额">
              <el-input-number v-model="orderForm.sum" placeholder="工单金额" :min=0></el-input-number>
              <span class="px-2">元</span>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-col :span="10">
              <el-form-item label="位置信息" prop="formattedAddress">
                <el-button @click="clickSetLocationBtn">
                  {{ orderForm.formattedAddress == null ? '点击获取位置' : orderForm.formattedAddress }}
                </el-button>
              </el-form-item>
            </el-col>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="10">
            <el-form-item label="服务地址">
              <el-input v-model="orderForm.serviceAddress" type="textarea" :rows="2" placeholder="服务地址" maxlength="200"
                show-word-limit></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <!-- <el-form-item label="工单描述" prop="orderDescription">
                                    <el-input v-model="form.orderDescription" type="textarea" :rows="2"
                                        placeholder="工单描述" maxlength="50" show-word-limit></el-input>
                                </el-form-item> -->
            <el-form-item label="服务要求">
              <el-input v-model="orderForm.serviceRequest" type="textarea" :rows="2" placeholder="服务要求" maxlength="200"
                show-word-limit></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="20">
            <el-form-item label="联系方式">
              <el-checkbox v-model="contacType1" @change="handleCheckboxChange('customer')">客户</el-checkbox>
              <el-checkbox v-model="contacType2" @change="handleCheckboxChange('onsite')">现场</el-checkbox>
              <el-checkbox v-model="contacType3" @change="handleCheckboxChange('agent')">代理</el-checkbox>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="contacType1">
          <el-col :span="20">
            <div v-for="(contact, index) in contacts.customer" :key="index">
              <el-form-item label="客户:">
                <el-input placeholder="联系人" v-model="contact.name" class="inputStyle"></el-input>
                <el-input placeholder="联系方式" v-model="contact.info" class="inputStyle"></el-input>
                <el-button @click="addContact('customer')" class="iconStyle" link><el-icon>
                    <CirclePlus />
                  </el-icon></el-button>
                <el-button @click="removeContact('customer', index)" class="iconStyle" link><el-icon>
                    <Remove />
                  </el-icon></el-button>
              </el-form-item>
            </div>
          </el-col>
        </el-row>

        <el-row v-if="contacType2">
          <el-col :span="20">
            <div v-for="(contact, index) in contacts.onsite" :key="index">
              <el-form-item label="现场:">
                <el-input placeholder="联系人" v-model="contact.name" class="inputStyle"></el-input>
                <el-input placeholder="联系方式" v-model="contact.info" class="inputStyle"></el-input>
                <el-button @click="addContact('onsite')" class="iconStyle" link><el-icon>
                    <CirclePlus />
                  </el-icon></el-button>
                <el-button @click="removeContact('onsite', index)" class="iconStyle" link><el-icon>
                    <Remove />
                  </el-icon></el-button>
              </el-form-item>
            </div>
          </el-col>
        </el-row>

        <el-row v-if="contacType3">
          <el-col :span="20">
            <div v-for="(contact, index) in contacts.agent" :key="index">
              <el-form-item label="代理:">
                <el-input placeholder="联系人" v-model="contact.name" class="inputStyle"></el-input>
                <el-input placeholder="联系方式" v-model="contact.info" class="inputStyle"></el-input>
                <el-button @click="addContact('agent')" class="iconStyle" link><el-icon>
                    <CirclePlus />
                  </el-icon></el-button>
                <el-button @click="removeContact('agent', index)" class="iconStyle" link><el-icon>
                    <Remove />
                  </el-icon></el-button>
              </el-form-item>
            </div>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="20">
            <el-form-item label="备件申请">
              <el-switch v-model="orderForm.needSpareParts" active-text="需要" inactive-text="不需要"></el-switch>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 备件申请相关内容 -->
        <div v-if="orderForm.needSpareParts" class="mt-4 bg-blue-50 p-4 rounded-lg border border-blue-100">
          <el-form-item label="选择备件">
            <el-button type="primary" size="small" @click="handleProductDialog" class="transition-all hover:shadow-md">
              选择产品部件
            </el-button>
          </el-form-item>

          <div class="grid grid-cols-1 md:grid-cols-2 gap-6 mt-4">
            <el-form-item label="审批人" prop="reviewer">
              <el-select v-model="orderForm.applyPartsDto.reviewer" placeholder="请选择审批人" style="width: 100%">
                <el-option v-for="item in approverOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>

            <el-form-item label="抄送" prop="copyIn">
              <el-select v-model="orderForm.applyPartsDto.copyIn" multiple placeholder="请选择抄送人" style="width: 100%">
                <el-option v-for="item in approverOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </div>

          <div class="grid grid-cols-1 md:grid-cols-2 gap-6 mt-4">
            <el-form-item label="申请事由" prop="reason">
              <el-input type="textarea" :rows="3" v-model="orderForm.applyPartsDto.reason" placeholder="请输入申请事由"
                class="textarea-focus"></el-input>
            </el-form-item>

            <el-form-item label="紧急程度" prop="urgency">
              <el-radio-group v-model="orderForm.applyPartsDto.urgency">
                <el-radio :value="1" class="radio-button-custom">普通</el-radio>
                <el-radio :value="2" class="radio-button-custom">紧急</el-radio>
                <el-radio :value="3" class="radio-button-custom">特急</el-radio>
              </el-radio-group>
            </el-form-item>
          </div>

          <div class="mt-4">
            <el-form-item label="附件">
              <el-upload action="#" :file-list="orderForm.applyPartsDto.attachments" multiple
                :http-request="handleApprovalUpload" :on-remove="handleApprovalRemove" :auto-upload="true">
                <el-button size="small" type="primary" class="transition-all hover:shadow-md">点击上传</el-button>
                <div slot="tip" class="el-upload__tip text-sm text-gray-500 mt-1">支持上传多个文件，单个文件不超过10MB</div>
              </el-upload>
            </el-form-item>
          </div>
        </div>
        <el-row>
          <el-col :span="20">
            <el-form-item label="是否指派" prop="isAssigned">
              <el-radio-group v-model="orderForm.isAssigned">
                <el-radio :value="1">是</el-radio>
                <el-radio :value="0">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>
    </FormDrawer>

    <!-- 工单管理员评价 -->
    <FormDrawer ref="formDrawerRef_score" title="内部评分" @submit="handleSubmit_score">
      <el-form-item v-for="item in form_score.labelMarks" :label="item.labelName" label-width="150px"
        label-position="left">
        <el-rate v-if="form_score.isEdit == true" v-model="item.mark" />
        <el-rate v-else v-model="item.mark" disabled />
      </el-form-item>
      <el-form-item label="工单评价" label-width="150px">
        <el-input v-if="form_score.isEdit == true" type="textarea" :rows="4" v-model="form_score.remark"
          placeholder="工单评价"></el-input>
        <el-input v-else type="textarea" :rows="4" v-model="form_score.remark" placeholder="工单评价" disabled></el-input>
      </el-form-item>
    </FormDrawer>

    <!-- 客户评分 -->
    <FormDrawer showSubBtn="0" ref="formDrawerRef_customerScore" title="客户评分">
      <div class="no-data" v-if="!form_customerScore.labelMarks.length && !form_purchaseScore.labelMarks.length">
        暂无评价数据
      </div>
      <div v-else>
        <el-collapse>
          <el-collapse-item v-for="(scoreData, scoreType, index) in scoreDataList"
            :title="scoreType === 'customer' ? '现场人员评价' : '采购人员评价'" :name="index + 1" :key="index">
            <template v-if="scoreData.labelMarks.length">
              <el-form-item v-for="item in scoreData.labelMarks" :label="item.labelName" label-width="150px"
                label-position="left" :key="item.labelName">
                <el-rate v-model="item.mark" disabled />
              </el-form-item>
              <el-form-item label="工单评价">
                <el-input type="textarea" :rows="4" v-model="scoreData.remark" placeholder="工单评价" disabled></el-input>
              </el-form-item>
            </template>
            <template v-else>
              <div class="no-data">{{ scoreType === 'customer' ? '暂无现场人员评价数据' : '暂无采购人员评价数据' }}</div>
            </template>
          </el-collapse-item>
        </el-collapse>
      </div>
    </FormDrawer>

    <!-- 发布工单 -->
    <el-dialog v-model="dialogTableVisible_orderPublish" title="发布工单" width="40%" align-center>
      <el-form :model="publishForm" ref="publishFormRef" :rules="publishFormRules" label-width="90px" :inline="false">
        <el-row>
          <el-col :span="12">
            <el-form-item label="发布方式" prop="publishType">
              <!-- 发布方式，1指派，2地图选择，3所有人抢单，4指定人抢单 -->
              <el-select v-model="publishForm.publishType" @change="publishTypeChange" placeholder="发布方式">
                <el-option key="1" label="由指派人选择执行人员" value="1" />
                <el-option key="3" label="所有人抢单" value="3" />
                <el-option key="4" label="指定人抢单" value="4" />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <div class="flex items-center justify-end">
              <el-button
                v-if="publishForm.publishType == 1 && assignProps.assignedUserId != null && assignProps.assignedUserId.length > 0"
                type="primary" text @click="handleAssign(editOrderId)">已指派</el-button>
              <el-button
                v-if="publishForm.publishType == 1 && (assignProps.assignedUserId == null || assignProps.assignedUserId.length == 0)"
                type="primary" text @click="handleAssign(editOrderId)">指派</el-button>
              <el-button v-if="publishForm.publishType == 4" type="primary" text
                @click="handleAssign(editOrderId)">选择人员</el-button>
              <el-button v-if="publishForm.publishType == 1 || publishForm.publishType == 4" type="primary" text
                @click="handleMapAssign(editOrderId)">查看指派地图</el-button>
            </div>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="default" @click="dialogTableVisible_orderPublish = false">
            关闭
          </el-button>
          <el-button type="primary" @click="orderPublish()">
            发布
          </el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 选择产品部件弹窗 -->
    <SystemDialog title="选择产品部件" :visible="dialogTableVisible_parts" :height="50" :width="70" :showOkBtn="true"
      @on-close="dialogTableVisible_parts = false" @on-confirm="confirmCheckedParts" :showCloseBtn="true"
      okBtnName="确认">
      <template v-slot:content>
        <ProductSelection v-if="dialogTableVisible_parts" :selectedParts="preSelectedParts"
          @getCheckedPart="getCheckedPart" />
      </template>
    </SystemDialog>

    <!-- 选取产品dialog -->
    <SystemDialog title="选择产品" :visible="dialogTableVisible_product" :height="60" :width="70"
      @on-close="dialogTableVisible_product = false" @on-confirm="confirmCheckedProduct" :showCloseBtn="true"
      :showOkBtn="true" okBtnName="选择产品">
      <template v-slot:content>
        <SelectProduct v-if="dialogTableVisible_product" @getCheckedProduct="getCheckedProduct" />
      </template>
    </SystemDialog>

    <!-- 添加备件弹窗 -->
    <el-dialog :title="drawerPartTitle" v-model="formDrawerRef" width="40%" align-center>
      <el-form :model="partForm" ref="formPartRef" label-width="120px" :inline="false" :rules="partRules">
        <el-form-item label="品名" prop="partName">
          <el-input v-model="partForm.partName" placeholder="品名"></el-input>
        </el-form-item>
        <el-form-item label="部件序列号" prop="partSn">
          <el-input v-model="partForm.partSn" placeholder="部件序列号"></el-input>
        </el-form-item>
        <el-form-item label="型号规格" prop="partTypeId">
          <el-input v-model="partForm.partTypeId" placeholder="型号规格"></el-input>
        </el-form-item>
        <el-form-item label="物料编码" prop="materialCode">
          <el-input v-model="partForm.materialCode" placeholder="物料编码"></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input v-model="partForm.remarks" placeholder="备注"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="formDrawerRef = false">取 消</el-button>
          <el-button type="primary" @click="submitPartForm">确 定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 新增产品弹窗 -->
    <el-dialog :title="productDialogTitle" v-model="productDialogVisible" width="60%" align-center>
      <el-form :model="productForm" ref="productFormRef" :rules="productRules" class="form-inline" :inline="false">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="产品型号" prop="productTypeId">
              <el-select placeholder="请选择产品型号" v-model="productForm.productTypeId" style="width: 100%">
                <el-option v-for="(item, index) in productTypeMenuGroups" :key="index" :label="item.productTypeCode"
                  :value="item.productTypeId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="整机序列号" prop="oeSerialNo">
              <el-input v-model="productForm.oeSerialNo" placeholder="整机序列号"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="ERP" prop="erpNo">
              <el-input v-model="productForm.erpNo" placeholder="项目编码/ERP"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="买方" prop="customerId">
              <el-button @click="dialogTableVisible_product_company = true">
                {{
                checkedProductCustomer == null ? "选择买方" : checkedProductCustomer.name
                }}
              </el-button>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="终端客户" prop="supplierId">
              <el-button @click="dialogTableVisible_product_supplier = true">
                {{
                checkedProductSupplier == null ? "选择终端客户" : checkedProductSupplier.name
                }}
              </el-button>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="软件版本" prop="softwareVersion">
              <el-input v-model="productForm.softwareVersion" placeholder="软件版本"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="发货日期">
              <el-date-picker v-model="productForm.deliveryDate" type="datetime" placeholder="选择日期"
                format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss" style="width: 100%"></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="完工日期">
              <el-date-picker v-model="productForm.completionDate" type="datetime" placeholder="选择日期"
                format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss" style="width: 100%"></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="交船日期">
              <el-date-picker v-model="productForm.shipDeliveryDate" type="datetime" placeholder="选择日期"
                format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss" style="width: 100%"></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="质保截至日期">
              <el-date-picker v-model="productForm.warrantyEndDate" type="datetime" placeholder="选择日期"
                format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss" style="width: 100%"></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="质保条款">
              <el-radio-group v-model="productForm.warrantyType" @change="handleProductRadioChange">
                <el-radio value="交船后">交船后</el-radio>
                <el-radio value="发货后">发货后</el-radio>
              </el-radio-group>
              <template v-if="productForm.warrantyType">
                <el-input v-model="productForm.warrantyMonths" placeholder="请输入月份" @input="handleProductWarrantyTypeChange"
                  style="width: 100px; margin-left: 10px;"></el-input>
                <span style="margin-left: 10px;">个月</span>
              </template>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="productDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitProductForm">确 定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 选择买方dialog -->
    <SystemDialog title="选择买方" :visible="dialogTableVisible_product_company" :height="60" :width="70"
      @on-close="dialogTableVisible_product_company = false" @on-confirm="dialogTableVisible_product_company = false"
      :showCloseBtn="true" :showOkBtn="true" okBtnName="确认" cancelBtnName="取消">
      <template v-slot:content>
        <SelectCompany v-if="dialogTableVisible_product_company" :selectedCompanyId="productForm.customerId"
          @getCheckedCompany="getCheckedProductCompany" :showSelection="true" />
      </template>
    </SystemDialog>
    <!-- 选择终端客户dialog -->
    <SystemDialog title="选择终端客户" :visible="dialogTableVisible_product_supplier" :height="60" :width="70"
      @on-close="dialogTableVisible_product_supplier = false" @on-confirm="dialogTableVisible_product_supplier = false"
      :showCloseBtn="true" :showOkBtn="true" okBtnName="确认" cancelBtnName="取消">
      <template v-slot:content>
        <SelectCompany v-if="dialogTableVisible_product_supplier" :selectedCompanyId="productForm.supplierId"
          @getCheckedCompany="getCheckedProductSupplier" :showSelection="true" />
      </template>
    </SystemDialog>
  </el-card>
</template>

<script setup>
import { onMounted, ref, reactive, computed, watch } from "vue";
import FormDrawer from "~/components/FormDrawer.vue";
import { useStore } from 'vuex'
import { toast, toastWarn } from "~/composables/util"
import { dateFormatterDay, addMonthsAndFormat } from '~/utils/common.js'
import { checkOrdName } from '~/utils/validate.js';
import { getDaysBetweenDates, delRepeatJson } from '~/utils/common.js';
import GaoDeMap from "~/components/GaoDeMap.vue";
import SystemDialog from "~/components/SystemDialog.vue";
import SelectProduct from "~/components/select-product.vue";
import SelectCompany from "~/components/select-company.vue";
import  ProductSelection  from '~/components/ProductSelection.vue';
import OrderLog from "~/components/order-log.vue";
import OrderFiles from "~/components/order-files.vue";
import SelectEngineer from "~/components/select-engineer.vue";
import SelectEngineerMap from "~/components/select-engineer-map.vue";
import {
    api_orders_add, api_orders_detail, api_orders_getScore, api_orders_list,
    api_orders_postScore, api_orders_scoreLabels, api_orders_update, api_project_constant,
    api_orders_delete, api_orders_getCustomerScore, api_orders_dispatch
} from "~/api/ordersApi"
import { api_ship_uploadFile, getShipInfo } from "~/api/supply"
import { updateShipId, getProductList, uploadFile, batchCreateProduct, addProduct, updateProduct, getProductTypeByType } from "~/api/productApi"
import { addProductPart, deleteProductPart, updateProductPart, getProductPartList } from "~/api/productApi";
import { getUserByRole } from "~/api/userApi";



const projectActiveNames = ref(['shipInfo'])
//store存储
const store = useStore()
//界面传参：船舶ID
const shipId = ref(null)

//页面常量---------------
const projectStatuses = ref([])
const orderStatusList = ref([])
const orderTypes = ref([])
//页面常量---------------

//船舶信息---------------
const shipDetail = ref({
  id: null,
  name: "",
  imo: "",
  mmsi: "",
  createTime: "",
  shipType: "",
  projectId: "",
  projectName: "",
});
//船舶类型常量列表
const shipTypeList = ref([])
//获取船舶资料
const getShipDetail = async () => {
  let rspDto = await getShipInfo(shipId.value)
  shipDetail.value = rspDto
  shipDetail.value.createTime = dateFormatterDay(shipDetail.value.createTime)
  shipDetail.value.shipType = formatShipType(shipDetail.value.shipType)
}

function formatShipType (shipType){
    return shipTypeList.value.find(x => x.code == shipType)?.description || shipType
}
//--------------------------

//产品信息-------------------
const dialogTableVisible_product = ref(false)
function selectProduct() {
  dialogTableVisible_product.value = true
}
// 新增产品相关
const productDialogVisible = ref(false);
const productDialogTitle = ref("新增产品");
const productEditId = ref(0);
const productFormRef = ref(null);
const productTypeMenuGroups = ref([]);
const dialogTableVisible_product_company = ref(false);
const dialogTableVisible_product_supplier = ref(false);
const checkedProductCustomer = ref(null);
const checkedProductSupplier = ref(null);

const productForm = reactive({
  oeSerialNo: "",
  softwareVersion: "",
  supplierId: "",
  customerId: "",
  deliveryDate: "",
  completionDate: "",
  shipDeliveryDate: "",
  warrantyEndDate: "",
  warrantyTerms: "",
  productTypeId: "",
  factory: "",
  erpNo: "",
  warrantyMonths: "",
  warrantyType: "",
  shipId: null,
});

const productRules = {
  productTypeId: [
    { required: true, message: '产品型号不能为空', trigger: 'change' }
  ],
};

// 打开新增产品弹窗
const openAddProductDialog = () => {
  productDialogTitle.value = "新增产品";
  productEditId.value = 0;
  checkedProductSupplier.value = null;
  checkedProductCustomer.value = null;
  resetProductForm({
    oeSerialNo: "",
    softwareVersion: "",
    supplierId: "",
    customerId: "",
    deliveryDate: "",
    completionDate: "",
    shipDeliveryDate: "",
    warrantyEndDate: "",
    warrantyTerms: "",
    productTypeId: "",
    factory: "",
    erpNo: "",
    warrantyMonths: "",
    warrantyType: "",
    shipId: null,
  });
  // 加载产品类型列表
  loadProductTypeList();
  productDialogVisible.value = true;
};

// 加载产品类型列表
const loadProductTypeList = () => {
  // 根据船舶信息判断产品来源，这里默认使用HLD，可以根据实际情况调整
  const source = 'HLD'; // 可以从shipDetail中获取或根据业务逻辑判断
  getProductTypeByType(source).then(res => {
    productTypeMenuGroups.value = res || [];
  });
};

// 获取选择的买方
function getCheckedProductCompany(data) {
  if (data != null) {
    productForm.customerId = data.id;
    checkedProductCustomer.value = data;
  }
}

// 获取选择的终端客户
function getCheckedProductSupplier(data) {
  if (data != null) {
    productForm.supplierId = data.id;
    checkedProductSupplier.value = data;
  }
}

const handleProductRadioChange = () => {
  if (productForm.warrantyMonths) {
    productForm.warrantyMonths = "";
    productForm.warrantyEndDate = "";
  }
};

const handleProductWarrantyTypeChange = () => {
  const monthsToAdd = parseInt(productForm.warrantyMonths, 10);
  if (productForm.warrantyType === '发货后' && productForm.deliveryDate) {
    const warrantyEndDate = addMonthsAndFormat(productForm.deliveryDate, monthsToAdd);
    productForm.warrantyEndDate = warrantyEndDate;
  } else if (productForm.warrantyType === '交船后' && productForm.shipDeliveryDate) {
    const warrantyEndDate = addMonthsAndFormat(productForm.shipDeliveryDate, monthsToAdd);
    productForm.warrantyEndDate = warrantyEndDate;
  }
};

// 监听产品型号变化，自动设置factory
watch(() => productForm.productTypeId, (newVal) => {
  const selectedItem = productTypeMenuGroups.value.find(item => item.productTypeId === newVal);
  if (selectedItem) {
    productForm.factory = selectedItem.factory;
  }
});

// 提交产品表单
const submitProductForm = () => {
  productFormRef.value.validate((valid) => {
    if (!valid) return;
    if (productForm.warrantyType && productForm.warrantyMonths) {
      productForm.warrantyTerms = `${productForm.warrantyType}${productForm.warrantyMonths}个月`;
    }
    // 自动关联当前船舶
    productForm.shipId = shipId.value;
    const fun = productEditId.value ? updateProduct(productEditId.value, productForm) : addProduct(productForm);
    fun.then(res => {
      toast(productDialogTitle.value + "成功");
      productDialogVisible.value = false;
      // 刷新产品列表
      loadProductList();
    }).catch(err => {
      toast("提交失败", err);
    });
  });
};

// 重置产品表单
function resetProductForm(row = false) {
  if (productFormRef.value) productFormRef.value.resetFields();
  if (row) {
    for (const key in productForm) {
      // 如果是时间字段，去掉 .000 +00:00
      if (key.includes("Date") && row[key]) {
        productForm[key] = row[key].replace("T", " ").replace(".000+00:00", "");
      } else {
        productForm[key] = row[key];
      }
    }
  }
}

const form = reactive({
  oeSerialNo: "",
  softwareVersion: "",
  supplierId: "",
  customerId: "",
  deliveryDate: "",
  completionDate: "",
  shipDeliveryDate: "",
  warrantyEndDate: "",
  warrantyTerms: "",
  productTypeId: "",
  factory: "",
});

// 批量导入
const filesInfo = ref([])
const ruleForm = reactive({
  fileList: [],
})
const batchformDrawer = ref(false)
const handleImport = () => {
  ruleForm.fileList = [];
  filesInfo.value = [];
  batchformDrawer.value = true
}
const downloadTemplate = () => {
  window.location.href = "batchCreateTemplate.xlsx"
};
const handleChange = (file, fileList) => {
  form.files = fileList;
}
//上传文件
const handleUpload = (param) => {
  const File = param.file;
  let paramIo = new FormData();
  paramIo.append("file", File);
  uploadFile(paramIo).then((res) => {
    if(res.length > 0){
        filesInfo.value.push(res[0]);
      }
  });
}
const onSubmit = () => {
  if (filesInfo.value.length > 0) {
    batchCreateProduct(JSON.stringify(filesInfo.value),shipId.value).then(res => {
      toast("文件处理成功");
      // 关闭弹窗
      console.log('返回的结果:', JSON.stringify(res));
      filteredProducts.value = delRepeatJson(filteredProducts.value.concat(res), "productId")
      batchformDrawer.value = false;

    })
  } else {
    toastWarn("请选择文件");
  }
}

const filteredProducts = ref(null)
function loadProductList() {
  const params = {
    shipId: shipId.value,
    partsFlag:true,
  };
  getProductList(params).then(res => {
    filteredProducts.value = res?res.records:[]
  })

}

const transferProductStatus = (warrantyEndDate) => {
  if(warrantyEndDate && new Date(warrantyEndDate) < new Date()){
    return "保外";
  }else{
    return "保内"
}};

const expandedProduct = ref(null)
const currentProduct = ref(null)

const toggleProductExpand = (row) => {
  if (expandedProduct.value === row.productId) {
    expandedProduct.value = null
    currentProduct.value = null
  } else {
    expandedProduct.value = row.productId
    currentProduct.value = row
  }
  console.log('当前展开的产品:', JSON.stringify(currentProduct.value))
}
const handleProductSelect = (row) => {
  currentProduct.value = row
  if (row && !expandedProduct) {
    expandedProduct.value = row.productId
  }
}
const selectProductCheckList = ref(null)

function getCheckedProduct(val) {
    //console.log("回显数据===>",JSON.stringify(val))
    selectProductCheckList.value = val
}
//确认已选择的产品
function confirmCheckedProduct() {
    //去重回显
    if (null != selectProductCheckList.value && selectProductCheckList.value.length > 0) {
        if (null == filteredProducts.value || filteredProducts.value.length == 0) {
            filteredProducts.value = selectProductCheckList.value
        } else {
            filteredProducts.value = delRepeatJson(filteredProducts.value.concat(selectProductCheckList.value), "productId")
        }
        // 对每条选择的数据调用下游更新id
        selectProductCheckList.value.forEach(product => {
            let paramIo = {productId:product.productId,shipId:shipId.value}
           updateShipId(paramIo)
        });
        dialogTableVisible_product.value = false
    } else {
        toastWarn("您未选择产品")
    }
}

const removeProduct = (row) => {
  let paramIo = {productId:row.productId}
  updateShipId(paramIo)  
  filteredProducts.value = filteredProducts.value.filter(item => item.productId !== row.productId)
}

//--------------------------

//备件信息-------------------
const formDrawerRef = ref(false);
const formPartRef = ref(null);
const partEditId = ref(0)
const drawerPartTitle = computed(() => partEditId.value ? "修改" : "新增")
const workOrderList = ref([])
const partForm = reactive({
  productTypeId: null,
  productId: null,
  productTypeCode: null,
  partName: null,
  materialCode: null,
  partTypeId: null,
  partSn: null,
  remarks: null,
  price: 0,
  amount: 0,
});
//添加备件
const showAddSparePartDialog = () => {
  partEditId.value = 0
  resetForm({
    productTypeId: null,
    productId: null,
    productTypeCode: null,
    partName: null,
    materialCode: null,
    partTypeId: null,
    partSn: null,
   remarks: null,
    price: 0,
    amount: 0,
  })
  formDrawerRef.value = true;
}
//执行部件表单校验
const partRules = {
  partName: [
    { required: true, message: '部件名称不能为空', trigger: 'change' }
  ],
  partSn: [
    {required: true, message: '部件序列号不能为空', trigger: 'change' }
  ]

}

// 新增部件表单提交
const submitPartForm = () => {
 //表单校验
    formPartRef.value.validate((valid) => {
      if (!valid) return
      let paramIo = new FormData()// FormData 对象
      partForm.productId = currentProduct.value.productId;
      partForm.productTypeId = currentProduct.value.productTypeId;
      partForm.price =0
      partForm.amount =0
      for (let key in partForm) {
        paramIo.append(key, partForm[key])
      }
      paramIo.append("partId", partEditId.value)
      console.log('表单入参===={}',JSON.stringify(partForm))
      const fun = partEditId.value ? updateProductPart(partEditId.value, paramIo) : addProductPart(paramIo)  
        fun.then(res => {
          toast(drawerPartTitle.value + "成功")
          formDrawerRef.value = false; // 关闭弹窗
          if(partEditId.value){
            const index = currentProduct.value.productPartDto.findIndex(item => item.partId === partEditId.value)
            if(index !== -1){
              partForm.partId = partEditId.value
              currentProduct.value.productPartDto[index] = partForm
            }
            
          }else{
            currentProduct.value.productPartDto.push(partForm)
          }
        }).catch(err => {
        });
    })
}



  const editSparePart = (row) => {
    partEditId.value = row.partId
    resetForm(row)
    formDrawerRef.value = true;
  }

const removeSparePart = (partId) => {
  console.log('删除的备件信息:', JSON.stringify(partId))
  deleteProductPart(partId).then(res => {
  toast("删除成功")
  currentProduct.value.productPartDto=currentProduct.value.productPartDto.filter(part => part.partId !== partId);
  }).catch(err => { 
    toast("删除失败", err) })
}

  // 重置表单
  function resetForm(row = false) {
    if (formPartRef.value) formPartRef.value.resetFields()
    if (row) {
      for (const key in partForm) {
        partForm[key] = row[key]
      }
    }
  }

//--------------------------

//工单信息-------------------
const preSelectedParts = ref([])
const currentPage = ref(1)
const total = ref(0)
const limit = ref(10)
const loading = ref(false)
const editOrderId = ref(0)
const formOrderDrawerRef = ref(null)
const orderFormRef = ref(null)
const dialogTableVisible_parts = ref(false)
const address = ref("点击设置位置");
const setLocationDialogVisible = ref(false)
// 指派工单弹窗
const asignEngineerDialogVisible = ref(false)
const dialogTableVisible_orderPublish = ref(false)
// 已选工程师列表
const assignProps = reactive({
    assignedUserId: null,
    orderLocationDto: null
})
// 指派工单弹窗 map
const asignEngineerMapDialogVisible = ref(false)
const drawerOrderTitle = computed(() => editOrderId.value ? "修改" : "新增")
//联系方式
const contacType1 = ref(false)
const contacType2 = ref(false)
const contacType3 = ref(false)
const contacts = reactive({
    customer: [],
    onsite: [],
    agent: []
})
const orderForm = reactive({
    shipId: shipId.value,
    projectId:shipDetail.value.projectId,
    orderId: null,
    orderName: "",
    orderType: null,
    orderSource: null,
    deviceIds: [],
    //用于位置校验
    formattedAddress: null,
    locationCreateDto: {
        latitude: null,
        longitude: null,
        locationType: "1",
        formattedAddress: "",
        adcode: "",
        country: "",
        province: "",
        city: "",
        district: "",
        township: ""
    },
    //工单持续时间
    continuous: 0,
    //工单金额
    sum: 0,
    //工单描述
    orderDescription: "",
    //客户要求时间
    startTime: null,
    //预估工时
    estimatedHours: null,
    //服务地址
    serviceAddress: null,
    //联系方式
    //contactInfo: null,
    //客户
    customerName: null,
    customerContact: null,
    //现场
    onsiteName: null,
    onsiteContact: null,
    //代理
    agentName: null,
    agentContact: null,
    //服务要求
    serviceRequest: null,
    isAssigned: 1,
    needSpareParts: false,
    applyPartsDto:{
      reviewer: null,
      copyIn: null,
      reason:null,
      urgency:null,
      applyPartsInfoDto :ref([]),
      attachments:ref([])
    }
    
})
const orderRules = {
    orderName: [
        { validator: checkOrdName, required: true, trigger: 'blur' }
    ],
    orderType: [
        { required: true, message: '工单类型不能为空', trigger: 'change' }
    ],
    orderSource: [
        { required: true, message: '订单来源不能为空', trigger: 'change' }
    ],
    formattedAddress: [
        { required: true, message: '位置信息不能为空', trigger: 'change' }
    ]
}

const searchForm = reactive({
    orderNo: "",
    orderName: "",
    shipId: null,
    customerId: "",
    orderStatus: null,
    customerRating: null,
    page: currentPage.value,
    size: limit.value,
    startTime: '',
})
const resetSearchForm = () => {
    searchForm.orderNo = ""
    searchForm.orderName = ""
    searchForm.shipId = ""
    searchForm.customerId = ""
    searchForm.orderStatus = null
    searchForm.customerRating = null
    searchForm.startTime = ""
    // getData()
}

//联系人多选框，点击加减添加或者删除多个联系人
function handleCheckboxChange(value) {
    contacts[value] = [];
    if (value === 'customer' && contacType1 && contacts.customer.length === 0) {
        // 初始化第一个联系人
        contacts.customer.push({ name: '', info: '' });
    }
    else if (value === 'onsite' && contacType2 && contacts.onsite.length === 0) {
        contacts.onsite.push({ name: '', info: '' });
    } else if (value === 'agent' && contacType3 && contacts.agent.length === 0) {
        contacts.agent.push({ name: '', info: '' });
    }
}

function addContact(value) {
    contacts[value].push({
        name: null,
        info: null
    })
}

function removeContact(value, index) {
    contacts[value].splice(index, 1);
    if (value === 'customer' && contacts.customer.length === 0) {
        contacType1.value = false
    } else if (value === 'onsite' && contacts.onsite.length === 0) {
        contacType2.value = false
    } else if (value === 'agent' && contacts.agent.length === 0) {
        contacType3.value = false
    }
}

//新增工单提交
const handleOrderDialog = () => {
  editOrderId.value = 0
  resetOrderForm({
    shipId: shipId.value,
    projectId:shipDetail.value.projectId,
    orderId: null,
    orderName: "",
    orderType: null,
    orderSource: null,
    deviceIds: [],
    orderDescription: "",
    //工单客户信息与项目一致
    //customerId: checkedCustomer_project.value == null ? "" : checkedCustomer_project.value.id,
    //用于位置校验
    formattedAddress: null,
    locationCreateDto: {
      latitude: null,
      longitude: null,
      locationType: "1",
      formattedAddress: "",
      adcode: "",
      country: "",
      province: "",
      city: "",
      district: "",
      township: ""
    },
    //工单描述
    orderDescription: "",
    //客户要求时间
    startTime: null,
    //预估工时
    estimatedHours: null,
    //服务地址
    serviceAddress: null,
    //联系方式
    //contactInfo: null,
    //客户
    customerName: null,
    customerContact: null,
    //现场
    onsiteName: null,
    onsiteContact: null,
    //代理
    agentName: null,
    agentContact: null,
    //服务要求
    serviceRequest: null,
    isAssigned: 1,
    needSpareParts: false,
    applyPartsDto:{
      reviewer: null,
      copyIn: null,
      reason:null,
      urgency:null,
      applyPartsInfoDto :ref([]),
      attachments:ref([])
    }
  })
  //默认工单金额0
  orderForm.sum = 0
  //重置客户、现场、代理人信息
  contacType1.value = false
  contacType2.value = false
  contacType3.value = false
  contacts.customer = [];
  contacts.onsite = [];
  contacts.agent = [];
  preSelectedParts.value = []
  // 重置订单来源选择
  selectedOrderSource.value = ''
  formOrderDrawerRef.value.open()
}

// 编辑工单
const handleEdit = async (row) => {
    //当前为编辑
    editOrderId.value = row.orderId
    //根据id查询工单，获取地址信息进行回显
    let detail = await api_orders_detail(row.orderId)

    // console.log('row===>', JSON.stringify(row))
    //console.log('order detail===>', JSON.stringify(detail))

    //初始化联系方式展示框
    //客户
    if (null == row.customerName || "" == row.customerName) {
        contacType1.value = false
        contacts.customer = [];
    } else {
        contacType1.value = true
        const customerNames = row.customerName.split(';');
        const customerContacts = row.customerContact.split(';');
        contacts.customer = customerNames.map((name, index) => ({
            name: name.trim(),
            info: customerContacts[index] ? customerContacts[index].trim() : ''
        }));
    }
    if (null == row.onsiteName || "" == row.onsiteName) {
        contacType2.value = false
        contacts.onsite = [];
    } else {
        contacType2.value = true
        const onsiteNames = row.onsiteName.split(';');
        const onsiteContacts = row.onsiteContact.split(';');
        contacts.onsite = onsiteNames.map((name, index) => ({
            name: name.trim(),
            info: onsiteContacts[index] ? onsiteContacts[index].trim() : ''
        }));
    }
    //代理人
    if (null == row.agentName || "" == row.agentName) {
        contacType3.value = false
        contacts.agent = [];
    } else {
        contacType3.value = true
        const agentNames = row.agentName.split(';');
        const agentContacts = row.agentContact.split(';');
        contacts.agent = agentNames.map((name, index) => ({
            name: name.trim(),
            info: agentContacts[index] ? agentContacts[index].trim() : ''
        }));
    }

    //发布方式
    if (null != row.publishType) {
        row.publishType = row.publishType.toString();
    }

    resetOrderForm(row)

    //回显地址信息------
    orderForm.locationCreateDto = { ...detail.orderLocationDto }
    address.value = orderForm.locationCreateDto.formattedAddress
    orderForm.formattedAddress = orderForm.locationCreateDto.formattedAddress
    //回显地址信息------

    //回显备件申请
    orderForm.needSpareParts = detail.needSpareParts ===1
    orderForm.isAssigned = detail.isAssigned
    if (detail.needSpareParts &&null != detail.applyPartsDto && detail.applyPartsDto.applyPartsInfoDto.length > 0) {
        orderForm.applyPartsDto = {
        reviewer: detail.applyPartsDto.reviewer,
        copyIn: convertCopyInToIntegerArray(detail.applyPartsDto.copyIn) || [], 
        reason: detail.applyPartsDto.reason,
        urgency: detail.applyPartsDto.urgency,
        applyPartsInfoDto: detail.applyPartsDto.applyPartsInfoDto || [],
        attachments: detail.applyPartsDto.attachments || [],
        };
        preSelectedParts.value = orderForm.applyPartsDto.applyPartsInfoDto
    }
    console.log('preSelectedParts===>', JSON.stringify(preSelectedParts.value))

    // 更新全选状态
    if (orderForm.deviceIds && filteredProducts.value && filteredProducts.value.length > 0) {
        const allProductIds = filteredProducts.value.map(product => product.productId);
        checkAll.value = orderForm.deviceIds.length === allProductIds.length && 
            allProductIds.every(id => orderForm.deviceIds.includes(id));
    } else {
        checkAll.value = false;
    }

    //打开编辑弹窗
    formOrderDrawerRef.value.open()
}

    const convertCopyInToIntegerArray = (copyIn) => {
      return copyIn.map(id => parseInt(id, 10));
    };

function handleOrderSubmit() {
  orderFormRef.value.validate((valid) => {
    if (!valid) return
    //构建联系人参数
    orderForm.customerName = contacts.customer.map(contact => contact.name).join(';');
    orderForm.customerContact = contacts.customer.map(contact => contact.info).join(';');
    orderForm.onsiteName = contacts.onsite.map(contact => contact.name).join(';');
    orderForm.onsiteContact = contacts.onsite.map(contact => contact.info).join(';');
    orderForm.agentName = contacts.agent.map(contact => contact.name).join(';');
    orderForm.agentContact = contacts.agent.map(contact => contact.info).join(';');
    if (orderForm.deviceIds && Array.isArray(orderForm.deviceIds)) {
      orderForm.deviceIds = orderForm.deviceIds.map(id => id.toString()).join(',')
    }
    console.log(JSON.stringify(orderForm))
    const fun = editOrderId.value ? api_orders_update(editOrderId.value, orderForm) : api_orders_add(orderForm)
    fun.then(res => {
      toast(drawerOrderTitle.value + "成功")
      // 修改刷新当前页，新增刷新第一页
      getData(editOrderId.value ? false : 1)
      formOrderDrawerRef.value.close()
    }).finally(() => {
      formOrderDrawerRef.value.hideLoading()
    })
  })
}

// 重置工单表单
function resetOrderForm(row = false) {
    if (orderFormRef.value) orderFormRef.value.resetFields()
    if (row) {
        for (const key in orderForm) {
            orderForm[key] = row[key]
        }
        
        // 处理设备型号ID转换
        if (row.deviceIds && typeof row.deviceIds === 'string') {
            // 将逗号分隔的字符串转换为数组
            orderForm.deviceIds = row.deviceIds.split(',').map(id => parseInt(id.trim())).filter(id => !isNaN(id));
        } else if (!row.deviceIds) {
            orderForm.deviceIds = [];
        }
    }
}



// 点击发布按钮
const showPublishWin = async (row) => {
    //置空数据------
    publishForm.formattedAddress = null
    publishForm.locationCreateDto = {
        latitude: null,
        longitude: null,
        locationType: "1",
        formattedAddress: "",
        adcode: "",
        country: "",
        province: "",
        city: "",
        district: "",
        township: ""
    }
    //发布方式
    publishForm.publishType = "1"
    //选择的工程师ids
    publishForm.engineerIds = null
    //已选择的工程师
    assignProps.assignedUserId = null
    //置空数据------

    //赋值工单id
    publishForm.orderId = row.orderId
    //工单详情
    let detail = await api_orders_detail(row.orderId)

    //回显地址信息------
    publishForm.locationCreateDto = { ...detail.orderLocationDto }
    publishForm.formattedAddress = publishForm.locationCreateDto.formattedAddress
    //回显地址信息------

    //回显发布方式、已选工作人员
    if (null != detail.orderDto.publishType) {
        publishForm.publishType = detail.orderDto.publishType.toString()
    }
    //发布方式，1指派，2地图选择，3所有人抢单，4指定人抢单
    //工单状态（1:未派发, 2:已派发,3工程师已接单，4工程师已出发，5:已开始,6施工已结束，7:已回款, 8:工单已完结）
    // console.log(JSON.stringify(detail.orderDto.publishType))
    // console.log(JSON.stringify(detail.orderDto.orderStatus))
    if (detail.orderDto.publishType == 4 && detail.orderDto.orderStatus < 3) {
        if (null != detail.orderDto.preEngineerIds) {
            let ids = detail.orderDto.preEngineerIds
            assignProps.assignedUserId = ids.split(',')
        }
    } else {
        if (null != detail.orderDto.engineerIds) {
            let ids = detail.orderDto.engineerIds
            assignProps.assignedUserId = ids.split(',')
        }
    }
    //回显发布方式、已选工作人员

    dialogTableVisible_orderPublish.value = true
}

// 发布工单
const orderPublish = () => {
    publishFormRef.value.validate((valid) => {
        if (!valid) return

        //先清空已选工程师ids
        publishForm.engineerIds = null

        //0 地图选择 1 由指派人选择执行人员 2 所有人抢单 3 指定人抢单
        //发布方式，1指派，2地图选择，3所有人抢单，4指定人抢单
        if (publishForm.publishType == 1 || publishForm.publishType == 4) {
            if (null != assignProps.assignedUserId && assignProps.assignedUserId.length > 0) {
                //选择工程师
                publishForm.engineerIds = assignProps.assignedUserId
            } else {
                toastWarn("请选择工程师")
                return
            }
        }
        const fun = api_orders_dispatch(publishForm)
        fun.then(res => {
            toast("发布成功")
            dialogTableVisible_orderPublish.value = false
            //刷新工单列表
            getData()
        })
    })
}

// 点击指派按钮
const handleAssign = (orderId) => {
    asignEngineerDialogVisible.value = true
}

// 点击指派按钮 map
const handleMapAssign = (orderId) => {
    if (null == publishForm.formattedAddress) {
        toastWarn("请先选择工单位置")
        return
    }
    //传递工单位置参数
    assignProps.orderLocationDto = publishForm.locationCreateDto
    asignEngineerMapDialogVisible.value = true
}

function addTimestamp() {
    const regex = /^[^-]+-[^-]+$/;
    const currentDate = new Date().toISOString().split('T')[0].replace(/-/g, '');
    if (!orderForm.orderName.includes(currentDate)) {
        orderForm.orderName = `${orderForm.orderName}-${currentDate}`;
    }
}


// 提交地图地址
const commitAddress = () => {
    // 提交地图地址
    // 关闭地图
    setLocationDialogVisible.value = false;
}

// 关闭地图
const closeAddress = () => {
    address.value = "";
    // 关闭地图
    setLocationDialogVisible.value = false;
}

// 点击设置位置信息btn
function clickSetLocationBtn() {
    setLocationDialogVisible.value = true;
}

// 获取选取位置
const getAddress = (data) => {
    if (data != "") {
        address.value = data;
        orderForm.formattedAddress = data;
    }
}

// 地图选位置
function addressClick(item, lng, lat) {
    address.value = `${item.regeocode.formattedAddress}`;
    orderForm.formattedAddress = `${item.regeocode.formattedAddress}`;
    orderForm.locationCreateDto = {
        latitude: lat,
        longitude: lng,
        locationType: "1",
        formattedAddress: item.regeocode.formattedAddress,
        adcode: item.regeocode.addressComponent.adcode,
        country: item.regeocode.addressComponent.country,
        province: item.regeocode.addressComponent.province,
        city: item.regeocode.addressComponent.city,
        district: item.regeocode.addressComponent.district || item.regeocode.addressComponent.province,
        district: item.regeocode.addressComponent.township,
    }
    //回显到服务地址字段
    orderForm.serviceAddress = orderForm.formattedAddress
}

// 获取工单数据
function getData(p = null) {
    if (typeof p == "number") {
        currentPage.value = p
    }
    loading.value = true
    //项目id
    searchForm.shipId = shipId.value
    searchForm.page = currentPage.value
    api_orders_list(searchForm)
        .then(res => {
            console.log('order list: ', res)
            workOrderList.value = res.records
            total.value = res.total
            currentPage.value = res.current
        })
        .finally(() => {
            loading.value = false
        })
}

// 获取订单状态等常量
function getProjectConstant() {
  api_project_constant().then(res => {
    console.log('项目常量:', JSON.stringify(res))
    orderStatusList.value = res?.orderStatuses
    orderTypes.value = res?.orderTypes
    projectStatuses.value = res?.projectStatuses
    shipTypeList.value = res?.shipTypeList
  })
}

// 转换订单状态函数
const formatOrderStatus = (state) => {
    return orderStatusList.value.find(x => x.code == state).description
}

// 转换工单类型函数
const formatOrderType = (state) => {
    return orderTypes.value?.find(x => x.code == state).description
}

// 全选状态
const checkAll = ref(false)

// 订单来源相关
const selectedOrderSource = ref('')
const showOrderSourceDropdown = ref(false)

// 处理订单来源选择
const handleOrderSourceSelect = (value) => {
    if (value) {
        // 如果当前orderForm.orderSource为空或者不包含选中的前缀，则设置为选中的值
        if (!orderForm.orderSource || !orderForm.orderSource.startsWith(value)) {
            orderForm.orderSource = value
        }
        // 将焦点设置到输入框，让用户可以继续输入后缀
        setTimeout(() => {
            const input = document.querySelector('input[placeholder="请选择或输入订单来源"]')
            if (input) {
                input.focus()
                // 将光标移动到末尾
                const len = input.value.length
                input.setSelectionRange(len, len)
            }
        }, 100)
    }
}

// 处理全选设备型号
const handleCheckAll = (checked) => {
    if (checked) {
        // 全选：将所有产品的型号添加到选择中
        orderForm.deviceIds = filteredProducts.value.map(product => product.productId)
    } else {
        // 取消全选：清空选择
        orderForm.deviceIds = []
    }
}

// 监听设备选择变化，更新全选状态
watch(() => orderForm.deviceIds, (newVal) => {
    if (!filteredProducts.value || filteredProducts.value.length === 0) {
        checkAll.value = false
        return
    }
    
    const allProductIds = filteredProducts.value.map(product => product.productId)
    checkAll.value = newVal && newVal.length === allProductIds.length && 
        allProductIds.every(id => newVal.includes(id))
}, { deep: true })


//发布工单表单---------------
const publishFormRef = ref(null)

const publishForm = reactive({
    orderId: null,
    //用于位置校验
    formattedAddress: null,
    locationCreateDto: {
        latitude: null,
        longitude: null,
        locationType: "1",
        formattedAddress: "",
        adcode: "",
        country: "",
        province: "",
        city: "",
        district: "",
        township: ""
    },
    //发布方式
    publishType: null,
    //选择的工程师ids
    engineerIds: null
})
const publishFormRules = {
    publishType: [
        { required: true, message: '发布方式不能为空', trigger: 'change' }
    ]
}
//---------------------------

// 工单指派工程师---------------------------------

const publishTypeChange = (val) => {
    // console.log("publishTypeChange==>",val)
    if (undefined == val || null == val) {
        publishForm.publishType = null
    }
    //清空已选工程师
    assignProps.assignedUserId = null
    assignProps.orderLocationDto = null
}

const getCheckedEngineer = (checkedEngineerIds) => {
    //console.log("getCheckedEngineer==>",checkedEngineerIds)
    assignProps.assignedUserId = checkedEngineerIds
}

// 提交指派工程师
const commitAssignEngineer = () => {
    //console.log("commitAssignEngineer===")
    if (null != assignProps.assignedUserId && assignProps.assignedUserId.length > 0) {
        asignEngineerDialogVisible.value = false;
    } else {
        toastWarn("您未选择工程师")
    }
}

// 关闭指派工程师
const closeAssignEngineer = () => {
    // 关闭地图
    asignEngineerDialogVisible.value = false;
}


// map
const getCheckedMapEngineer = (checkedEngineerIds) => {
    //console.log("getCheckedMapEngineer==>",checkedEngineerIds)
    assignProps.assignedUserId = checkedEngineerIds
}

// 提交指派工程师 map
const commitAssignMapEngineer = () => {
    if (null != assignProps.assignedUserId && assignProps.assignedUserId.length > 0) {
        asignEngineerMapDialogVisible.value = false;
    } else {
        toastWarn("您未选择工程师")
    }
}

// 关闭指派工程师 map
const closeAssignMapEngineer = () => {
    // 关闭地图
    asignEngineerMapDialogVisible.value = false;
}

// 工单指派工程师---------------------------------

//更多按钮操作------------------------------------

//工单附件
const dialogTable_orderFiles_title = ref(null)
const dialogTable_orderFiles_type = ref(null)
const dialogTableVisible_orderFiles = ref(false)
const currOrderFiles_orderId = ref(null)
//工单管理员评价
const formDrawerRef_score = ref(null)
const form_score = reactive({
    //是否可编辑
    isEdit: false,
    orderId: null,
    mark: 1,
    remark: "",
    labelMarks: []
})

// 客户评分------------
const formDrawerRef_customerScore = ref(null)
const form_customerScore = reactive({
    orderId: null,
    remark: "",
    labelMarks: []
})
const form_purchaseScore = reactive({
    orderId: null,
    remark: "",
    labelMarks: []
})
const scoreDataList = computed(() => ({
    customer: form_customerScore,
    purchase: form_purchaseScore
}))
const dialogTableVisible_orderLog = ref(false)
const currOrderLog_orderDetail = ref(null)

const handleCommand = (command) => {
  switch (command.action) {
    case 'handleOrderLog':
      handleOrderLog(command.row)
      break
    case 'handleOrderPayment':
      handleOrderPayment(command.row.orderId)
      break
    case 'handleOrderOver':
      handleOrderOver(command.row.orderId)
      break
    case 'handleScore':
      handleScore(command.row)
      break
    case 'customerScore':
      customerScore(command.row)
      break
    case 'showFilesEn':
      showFilesEn(command.row)
      break
    case 'showFiles':
      showFiles(command.row)
      break
    case 'handleDelete':
      handleDelete(command.row.orderId)
      break
  }
}

// 点击日志按钮
const handleOrderLog = (row) => {
    currOrderLog_orderDetail.value = row
    dialogTableVisible_orderLog.value = true
}

// 打开工单附件弹窗
const showFiles = (row) => {
    dialogTable_orderFiles_title.value = "工单附件"
    dialogTable_orderFiles_type.value = 0
    currOrderFiles_orderId.value = row.orderId
    dialogTableVisible_orderFiles.value = true
}

// 打开施工档案弹窗
const showFilesEn = (row) => {
    dialogTable_orderFiles_title.value = "施工档案"
    dialogTable_orderFiles_type.value = 1
    currOrderFiles_orderId.value = row.orderId
    dialogTableVisible_orderFiles.value = true
}

// 确认已回款
const handleOrderPayment = (orderId) => {
    let form = {}
    form.orderId = orderId
    //1:未派发, 2:已派发,3工程师已接单，4工程师已出发，5:已开始,6施工已结束，7:已回款, 8:工单已完结
    form.orderStatus = 7
    const fun = api_orders_update(orderId, form)
    fun.then(res => {
        toast("操作成功")
        getData(false)
    })
}

// 确认结单
const handleOrderOver = (orderId) => {
    let form = {}
    form.orderId = orderId
    //1:未派发, 2:已派发,3工程师已接单，4工程师已出发，5:已开始,6施工已结束，7:已回款, 8:工单已完结
    form.orderStatus = 8
    const fun = api_orders_update(orderId, form)
    fun.then(res => {
        toast("操作成功")
        getData(false)
    })
}

// 点击评分按钮
const handleScore = async (row) => {
    //清空数据
    form_score.remark = ""
    form_score.labelMarks = []

    form_score.orderId = row.orderId
    // 查看之前评分
    let detail = await api_orders_getScore(row.orderId)
    if (detail) {
        for (const key in form_score) {
            form_score[key] = detail[key]
        }
        formDrawerRef_score.value.hideSubmitBtn()
        //已评价不可编辑
        form_score.isEdit = false
    } else {
        formDrawerRef_score.value.showSubmitBtn()
        let data = await api_orders_scoreLabels()
        form_score.labelMarks = data.map(x => {
            return { labelId: x.id, mark: 5, labelName: x.value }
        })
        //未评价可编辑
        form_score.isEdit = true
    }
    formDrawerRef_score.value.open()
}

// 点击查看客户评分
const customerScore = async (row) => {
    // 清空数据
    form_customerScore.remark = "";
    form_customerScore.labelMarks = [];
    form_purchaseScore.remark = "";
    form_purchaseScore.labelMarks = [];
    form_customerScore.orderId = row.orderId;
    form_purchaseScore.orderId = row.orderId;

    // 查看之前评分
    const [detail, purchase] = await Promise.all([
        api_orders_getCustomerScore(row.orderId, 0),
        api_orders_getCustomerScore(row.orderId, 2)
    ]);

    if (detail) {
        Object.assign(form_customerScore, detail);
    }
    if (purchase) {
        Object.assign(form_purchaseScore, purchase);
    }

    formDrawerRef_customerScore.value.open();

}

// 提交评价
const handleSubmit_score = () => {
    console.log(form_score)
    api_orders_postScore(form_score)
        .then(res => {
            toast('评价成功')
            formDrawerRef_score.value.close()
        })
        .catch(res => {
            // toastError('评价失败：' + res)
        })
}

// 删除工单
const handleDelete = (id) => {
    loading.value = true
    api_orders_delete(id).then(res => {
        toast("删除成功")
        getData()
    })
        .finally(() => {
            loading.value = false
        })
}



//备件申请-------------------------------------
const approverOptions = ref([])

const handleProductDialog = () => {
      dialogTableVisible_parts.value = true
}
// const handleAttachmentChange= (file, fileList) => {

// }

// const handleAttachmentRemove = (file, fileList) => {

// }

const handleApprovalUpload = (param) => {
  const File = param.file;
  let paramIo = new FormData();
  paramIo.append("file", File);
  api_ship_uploadFile(paramIo).then((res) => {
    console.log("上传成功:", JSON.stringify(res));
    orderForm.applyPartsDto.attachments.push(...res); // 将 res 中的内容推入到 attachments 数组中
    toast("上传成功");
  }).catch((error) => {
    console.error("上传失败:", error);
    toast("上传失败，请重试");
  });
};

const handleApprovalRemove = (index) => {
  orderForm.applyPartsDto.attachments.splice(index, 1);
};

function confirmCheckedParts() {
    dialogTableVisible_parts.value = false

}
function getCheckedPart(checkedParts) {
  console.log("getCheckedPart==>",JSON.stringify(checkedParts))
  orderForm.applyPartsDto.applyPartsInfoDto = checkedParts
  preSelectedParts.value = checkedParts
}

function loadApprover() {
  getUserByRole(6).then(res => {
    approverOptions.value = res.map(x => {
      return { label: x.realName, value: x.id }
    })
  })
}
//备件申请-------------------------------------

// 获取设备型号名称
const getDeviceNames = (deviceIds) => {
  if (!deviceIds) return "-"
  
  let ids = deviceIds
  if (typeof deviceIds === 'string') {
    ids = deviceIds.split(',').map(id => parseInt(id.trim())).filter(id => !isNaN(id))
  }
  
  if (!Array.isArray(ids) || ids.length === 0) return "-"
  
  if (!filteredProducts.value || filteredProducts.value.length === 0) {
    return ids.join(', ')
  }
  
  const names = ids.map(id => {
    const product = filteredProducts.value.find(p => p.productId === id)
    return product ? product.productTypeCode : id
  })
  
  return names.join(', ')
}

// 生命周期函数
onMounted(() => {
  shipId.value = store.state.shipId
    // 获取界面所需常量
  getProjectConstant()
  getShipDetail()
  loadProductList()
  //获取工单列表
  getData()
  loadApprover()
})

</script>

<style lang="scss" scoped>
.basis-layout {
  max-height: 220px;
}

.product-title {
  font-size: 14px;
  font-weight: bold;
}

.section-title {
  margin-top: 0;
  margin-bottom: 5px;
  font-size: 14px;
  font-weight: bold;
}

.product-info {
  margin-bottom: 10px;
  padding: 5px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.product-info h6 {
  margin: 0 0 5px 0;
  color: #303133;
}

.product-info p {
  margin: 5px 0;
  color: #606266;
  font-size: 11px;
}

.empty-tip {
  height: 250px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.operation-buttons {
  display: flex;
  justify-content: space-between;
}

.operation-buttons .el-button {
  padding-left: 5px;
  padding-right: 5px;
  margin-right: 0;
  /* 调整按钮之间的间距 */
  width: inherit;
}

.operation-buttons .el-dropdown {
  padding-left: 5px;
  padding-right: 5px;
  margin-right: 0;
  /* 调整按钮之间的间距 */
  width: inherit;
}

.form-inline .el-input {
  --el-input-width: 150px;
}

.form-inline .el-select {
  --el-select-width: 150px;
}

.iconStyle {
    width: 18px;
    font-size: large;
}
.inputStyle {
    width: 213px;
    margin-right: 20px;
}

.no-data {
    text-align: center;
}
</style>